var dept=null,usedate=null;
$(function(){
	fillDepartments("groups");	
	$(".datepicker").datepicker({
		onSelect:function(date){
			usedate = date;
			getReport(date,dept);
		
		}
		
	});	
	var headable = false;
	$(window).bind('scroll',function(){		
	    if(!headable){
	    	var thds  = 	$("#dataTable thead tr:nth-child(2)").clone();
	      	$("#theader thead").append(thds);
	      	thds = $("#dataTable thead tr:nth-child(3)").clone();
	      	$("#theader thead").append(thds);
	    	headable = true;
	    	var tr = $("#pdtBody tr:nth-child(2)");
	        var tds = tr.children('td');
	    	var ths = $("#theader thead tr:nth-child(1) th");
	    	
	    	
	    	$(ths[0]).width($(tds[0]).width());
	    	$(ths[1]).width($(tds[1]).width());
	    	$(ths[2]).width($(tds[2]).width()*2+2);
	    	$(ths[3]).width($(tds[4]).width());
	    	$(ths[4]).width($(tds[5]).width()*2);
	    	$(ths[5]).width($(tds[7]).width()*2);
	    	$(ths[6]).width($(tds[9]).width()*2);
	    	$(ths[7]).width($(tds[11]).width()*2);
	    	$(ths[8]).width($(tds[13]).width());
	    	$(ths[9]).width($(tds[14]).width());
	    	$(ths[10]).width($(tds[15]).width());
	      
	    }
	    
	    var top = $(document).scrollTop();
	    if(top==0){
	    	$("#theader").hide();
	    }else{
	    	$("#theader").show();
	    }
	});
	
	$("#scode").bind('keyup',fireSearch);
	
});


function fireSearch(){
	
	var kc = event.keyCode;
	if(kc==13){
		$("#scode").focus();
		search();
	}
}

function search(){
	var key = $("#scode").val();
	if(key=='')return;
	var td = $("#pdtBody tr td:nth-child(1):contains('"+key+"')");
	var tr = td.parent().clone();
	$("#theader tbody").empty();
	$("#theader tbody").append(tr);
	$("#theader").show();
}
  

function fillDepartments(deptId) {
	var depts = $("#"+deptId);
	$.getJSON('admin/department/department!bytype',
			{
		      "bean.id":"root",
		      "bean.departmentType":"Manufacture"		
			},
			
		function(data, textStatus, jqXHR) {

		$.each(data, function(i, item) {
			var ipt = $("<button type='button' class='btn  btn-info' dept='"+item['id']+"'>"+item['name']+"</button>");
			ipt.bind("click",function(){
				
				var $this = $(this);
				departmentClicked($(this).attr("dept"),$(this).html());
				
				$this.removeClass("btn-info");
				$this.addClass("btn-success");
				
				var sbs = $this.siblings("button"); 
				$.each(sbs,function(idx,item){
		    		var other = $(item);
		    		other.removeClass("btn-success");
		    		other.addClass("btn-info");
		    	});
			});
			depts.append(ipt);			
		});	
		
	});
}
function departmentClicked(id,name){
	dept = id;
	$("#deptName").html(name);
	if(usedate==null)return;	
	getReport(usedate,id);
	
}
function getReport(date,id){
	if(id==null){		
		return;
	}
	
	var url = "views/data-view!viewreport";
	$.get(url,"usedate="+usedate+"&department.id="+dept,function(data){
		$("#a1").html(data);
	});
}

function showCalendar(id){
	$(".datepicker").datepicker('show');
}